<!-- 设备上下线日志 -->
<!-- 在线明细 -->
<template>
  <div>
    <Row :gutter="4" >
<!--      <Col span="3"><Dateselect ref="eventTime" v-model="dateRange" :placeholder="$t('select_date')"></Dateselect> </Col>
      <Col span="3"><Input clearable :placeholder="$t('device_code')" v-model="queryParam.where.deviceCode"></Input> </Col>-->
      <Col span="5"><DateTimeRangeSelect ref="eventTime" v-model="dateRange" :placeholder="$t('datetime')" width="100%"></DateTimeRangeSelect></Col>
      <Col span="4"><Device5gModelSelect :cate=2 ref="device5gModelSelect" width="100px" v-model="queryParam.where.deviceId"/> </Col>

      <Col span="3"><OrganizationTree ref="srhOrgSelect" width="200px" v-model="queryParam.where.orgId"></OrganizationTree> </Col>
      <Col span="3"><UserSelect ref="srhUserSelect" width="200px" v-model="queryParam.where.userId" :placeholder="$t('select_people')"></UserSelect> </Col>
      <Col span="3">
        <Select v-model="queryParam.where.action"
                :placeholder="$t('up_down_line_event')" clearable>
          <Option v-for="item in actions" :value="item.code" :key="item.code">{{ item.desc }}</Option>
        </Select>
      </Col>
      <Col span="1"><Button type="primary" icon="ios-search" @click="getData">{{$t('search')}}</Button></Col>
    </Row>

    <Table border :columns="columns" :data="tableData" :loading="tableLoading">
      <template slot-scope="{ row, index }" slot="map">
        <Button :disabled="!(!!row.locate)" type="default" :Title="$t('map')" icon="md-globe"
                style="margin-right: 3px" @click="openMap(row)"></Button>
      </template>
      <template slot-scope="{ row, index }" slot="udLine">
        <span v-if="row.action==0" style="color: red" >{{$t('down_line')}}</span>
        <span v-if="row.action==1" style="color: green">{{$t('up_line')}}</span>
      </template>
    </Table>
    <TopnavPage v-model="queryParam.page" @changePage="changePage"></TopnavPage>

    <Modal v-model="map.show" :title="map.title" width="730px">
      <div id="deviceMap" ref="deviceMap" style="height:500px;width:700px;background-color: #FFFFFF"></div>
    </Modal>
  </div>
</template>
<script>
import DateTimeRangeSelect from "_c/topnav/DateTimeRangeSelect"
import Device5gModelSelect from "_c/topnav/Device5gModelSelect";
import TopnavPage from "_c/topnav/TopnavPage";
import OrganizationTree from "_c/topnav/OrganizationTree";
import Dateselect from "_c/topnav/date2select"
import UserSelect from "_c/topnav/UserModelSelect";
import DeviceLogApi from "@/api/DeviceLog"
import EnumQuery from "@/api/EnumQuery";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import {pointStyle, polygonStyle} from "@/view/Home/map/maptools/tool/style";
import {genSource} from "@/view/Home/map/maptools/MapSource";
import {Map, View} from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import deviceItem from "../../map/maptools/img/user.png"
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {apiResult} from "@/libs/util";

export default {
  name: "DeviceOnlineLog",
  components:{TopnavPage,OrganizationTree,DateTimeRangeSelect,Device5gModelSelect,UserSelect},
  computed:{
    columns(){
      return [
        {title: this.$t('device_code'), key: 'deviceCode', sortable: true,width: 200,align: 'center',ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('device_name'), key: 'deviceName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('organization_name'), key: 'shortName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: this.$t('user_name'), key: 'userName', sortable: true, ellipsis:true,width: 175},
        {title: this.$t('time'), key: 'createTime', sortable: true,width: 250,align: 'center'},
        {title: this.$t('event'), key: 'actionStr', sortable: true, width: 120,slot:"udLine"},
        {title: this.$t('location'), key: 'locate', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        {title: '', key: 'actionStr', sortable: true, width: 80,slot:"map"},
      ]
    }
  },
  data(){
    return{
      map:{
        title: this.$t('location'),
        show:false,
        obj:null,
        mapInfo:null,
        customLayers:{
          layerVector: new LayerVector(),
          sourceVector: new SourceVector(),
        },
      },
      value14:null,
      api: new DeviceLogApi(),
      enumQuery: new EnumQuery(),
      actions:[],
      queryParam:{
        page: {
          //desc: ['create_time'],
          pages: 1,
          size: 15,
          total: 0,
          current: 1,
        },
        where: {
          keyword:null,
          deviceId: null,
          fromTime: null,
          toTime: null,
          userId: null,
          orgId: null,
          deviceCode:null,
          action:null
        },
      },
      tableData: [],
      tableLoading:false,
      dateRange:[]
    }

  },
  methods:{
    changePage(){
      this.getData()
    },
    getData(){
      this.tableLoading = true;
      /** 生成查询条件 */
      if (!(this.dateRange == null || this.dateRange.length < 2 || this.dateRange[0]=="")){
        this.queryParam.where.fromTime = this.dateRange[0];
        this.queryParam.where.toTime = this.dateRange[1];
      }
      this.api.queryPage(JSON.stringify(this.queryParam)).then(res => {
        this.tableData = null;
          apiResult(res.data,false,result=>{
            this.queryParam.page.total = result.data.total;
            this.tableData = result.data.records;
          })
        this.tableLoading = false;
      })
    },
    initMap(row){
      if (!!this.map.mapObj){
        this.map.mapObj.setTarget(null);
        this.map.mapObj.dispose()
        this.map.mapObj = null;
        this.map.customLayers.layerVector = null;
        this.map.customLayers.sourceVector = null;
      }
      this.map.mapInfo = new MapInfo().get();
      this.map.customLayers.layerVector =  new LayerVector();
      this.map.customLayers.sourceVector =  new SourceVector();
      this.map.customLayers.layerVector.setSource(this.map.customLayers.sourceVector);
      this.map.customLayers.layerVector.setStyle(polygonStyle);
      const that = this;

      const pos1 = row.locate.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(row.coordinateSystem,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      that.map.mapObj = new Map({
        target: "deviceMap", // 指向对象
        layers: [
          new TileLayer({
            source: new XYZ({
              //url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
              url: that.map.mapInfo.sub.url[0]
            }),
          })
        ],
        loadTilesWhileAnimating: true,//支持动画
        view: new View({
          projection: this.map.mapInfo.projection, //"EPSG:4326",
          center: pos,
          //center:[113.8417658402197,22.612941389571],
          zoom: 16,
        })
      });

      that.map.mapObj.addLayer(that.map.customLayers.layerVector);

      const point = new Feature({
        geometry: new Point(pos),
      });

      point.setStyle(pointStyle({online:row.action,title:row.deviceName}));
      this.map.customLayers.sourceVector.addFeature(point);
    },
    openMap(row) {
      this.map.show = true;
      //this.map.mapObj.updateSize();
      if (this.map.show) {
        this.$nextTick(() => {
          this.initMap(row);
        })
      }
    },
  },
  mounted() {
    /** 为了显示用，调置默认值 */
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);

    this.dateRange=[start, end];

    this.getData();

    /** 查询上下线事件 */
    this.enumQuery.get("EnumDeviceLogType").then(res => {
      apiResult(res.data,false,result=>{
        this.actions=[];
        if (!!res.data.data && res.data.data.length>0){
          res.data.data.forEach(item=>{
            this.actions.push(
              {
                code:item.code,
                desc:item.code===1?this.$t('up_line'):this.$t('down_line')
              }
            )
          })
        }
      })

    })


  }

}

</script>
<style>

</style>

